package com.dailytopic;

import java.util.*;

/**
 * @Author: huangzhigao
 * @Date: 2023/5/14 18:22
 */
public class Code1054 {
    public static int[] rearrangeBarcodes(int[] barcodes) {
        //先计数
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : barcodes) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        //大根堆存储，堆顶是元素数量最多的
        Queue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[0] - o1[0];
            }
        });


        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            queue.offer(new int[]{entry.getValue(), entry.getKey()});
        }

        int[] res = new int[barcodes.length];
        //每次从堆顶获取，如果堆顶元素与排列最后一个元素相等，取第二大的
        for (int i = 0; i < barcodes.length; i++) {
            int[] top = queue.poll();
            if (i == 0 || res[i - 1] != top[1]) {
                res[i] = top[1];
                if (top[0] - 1 != 0) {
                    queue.offer(new int[]{top[0] - 1, top[1]});
                }
            } else {
                int[] nextTop = queue.poll();
                res[i] = nextTop[1];
                if (nextTop[0] - 1 != 0) {
                    queue.offer(new int[]{nextTop[0] - 1, nextTop[1]});
                }
                queue.offer(new int[]{top[0], top[1]});
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] ns = {1,1,1,1,2,2,3,3};
        rearrangeBarcodes(ns);
    }
}
